Java Code Examples for org.apache.ranger.plugin.model.RangerServiceDef#getName()

The following examples show how to use org.apache.ranger.plugin.model.RangerServiceDef#getName() . 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: PublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/api/servicedef/name/{name}")
@PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
@Produces({ "application/json", "application/xml" })
public RangerServiceDef updateServiceDefByName(RangerServiceDef serviceDef,
                                     @PathParam("name") String name) {
	// serviceDef.name is immutable
	// if serviceDef.name is specified, it should be same as the param 'name'
	if(serviceDef.getName() == null) {
		serviceDef.setName(name);
	} else if(!serviceDef.getName().equals(name)) {
		throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "serviceDef name mismatch", true);
	}

	// ignore serviceDef.id - if specified. Retrieve using the given name and use id from the retrieved object
	RangerServiceDef existingServiceDef = getServiceDefByName(name);
	serviceDef.setId(existingServiceDef.getId());
	if(StringUtils.isEmpty(serviceDef.getGuid())) {
		serviceDef.setGuid(existingServiceDef.getGuid());
	}

	return serviceREST.updateServiceDef(serviceDef);
}
 
Example 2
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test6updateServiceDefByName() throws Exception {
	RangerServiceDef rangerServiceDef = rangerServiceDef();
	String name = rangerServiceDef.getName();
	Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef);
	Mockito.when(serviceREST.updateServiceDef(rangerServiceDef)).thenReturn(rangerServiceDef);
	RangerServiceDef dbRangerServiceDef = publicAPIsv2.updateServiceDefByName(rangerServiceDef, name);
	Assert.assertNotNull(dbRangerServiceDef);
	Assert.assertEquals(dbRangerServiceDef, rangerServiceDef);
	Assert.assertEquals(dbRangerServiceDef.getId(),
			rangerServiceDef.getId());
	Assert.assertEquals(dbRangerServiceDef.getName(),
			rangerServiceDef.getName());
	Mockito.verify(serviceREST).updateServiceDef(rangerServiceDef);
	Mockito.verify(serviceREST).getServiceDefByName(name);
}
 
Example 3
Source File: MetricUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
private VXMetricServiceCount getAuditsCount(int accessResult,
		Date startDate, Date endDate) throws Exception {
	long totalCountOfAudits = 0;
	SearchFilter filter = new SearchFilter();
	filter.setStartIndex(0);
	Map<String, Long> servicesRepoType = new HashMap<String, Long>();
	VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount();
	PList<RangerServiceDef> paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter);
	Iterable<RangerServiceDef> repoTypeGet = paginatedSvcDefs.getList();
	for (Object repo : repoTypeGet) {
		RangerServiceDef rangerServiceDefObj = (RangerServiceDef) repo;
		long id = rangerServiceDefObj.getId();
		String serviceRepoName = rangerServiceDefObj.getName();
		SearchCriteria searchCriteriaWithType = new SearchCriteria();
		searchCriteriaWithType.getParamList().put("repoType", id);
		searchCriteriaWithType.getParamList().put("accessResult", accessResult);
		searchCriteriaWithType.addParam("startDate", startDate);
		searchCriteriaWithType.addParam("endDate", endDate);
		VXAccessAuditList vXAccessAuditListwithType = assetMgr.getAccessLogs(searchCriteriaWithType);
		long toltalCountOfRepo = vXAccessAuditListwithType.getTotalCount();
		if (toltalCountOfRepo != 0) {
			servicesRepoType.put(serviceRepoName, toltalCountOfRepo);
			totalCountOfAudits += toltalCountOfRepo;
		}
	}
	vXMetricServiceCount.setServiceBasedCountList(servicesRepoType);
	vXMetricServiceCount.setTotalCount(totalCountOfAudits);
	return vXMetricServiceCount;
}
 
Example 4
Source File: RangerPolicyAdminCache.java    From ranger with Apache License 2.0 5 votes vote down vote up
private RangerPolicyAdmin addPolicyAdmin(ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) {
	RangerServiceDef    serviceDef          = policies.getServiceDef();
	String              serviceType         = (serviceDef != null) ? serviceDef.getName() : "";
	RangerPluginContext rangerPluginContext = new RangerPluginContext(new RangerPluginConfig(serviceType, null, "ranger-admin", null, null, options));
	RangerPolicyAdmin   ret                 = new RangerPolicyAdminImpl(policies, rangerPluginContext, roles);

	return ret;
}
 
Example 5
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test2getServiceDefByName() throws Exception {
	RangerServiceDef rangerServiceDef = rangerServiceDef();
	String name = rangerServiceDef.getName();
	Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef);
	RangerServiceDef dbRangerServiceDef = publicAPIsv2.getServiceDefByName(name);
	Assert.assertNotNull(dbRangerServiceDef);
	Assert.assertEquals(dbRangerServiceDef, rangerServiceDef);
	Assert.assertEquals(dbRangerServiceDef.getId(),
			rangerServiceDef.getId());
	Assert.assertEquals(dbRangerServiceDef.getName(),
			rangerServiceDef.getName());
	Mockito.verify(serviceREST).getServiceDefByName(name);
}
 
Example 6
Source File: TestPublicAPIsv2.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void test8deleteServiceDefByName() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerServiceDef rangerServiceDef = rangerServiceDef();
	String name = rangerServiceDef.getName();
	Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef);
	Mockito.doNothing().when(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request);
	publicAPIsv2.deleteServiceDefByName(name, request);
	Mockito.verify(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request);
	Mockito.verify(serviceREST).getServiceDefByName(name);
}
 
Example 7
Source File: RangerServiceDefHelper.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * Intended for use when serviceDef object is not-trusted, e.g. when service-def is being created or updated.
 * @param serviceDef
 * @param useCache
 */
public RangerServiceDefHelper(RangerServiceDef serviceDef, boolean useCache, boolean checkForCycles) {
	// NOTE: we assume serviceDef, its name and update time are can never by null.
	
	if(LOG.isDebugEnabled()) {
		LOG.debug(String.format("==> RangerServiceDefHelper(). The RangerServiceDef: %s", serviceDef));
	}

	String serviceName = serviceDef.getName();
	Date serviceDefFreshnessDate = serviceDef.getUpdateTime();

	Delegate delegate = null;
	if (useCache && _Cache.containsKey(serviceName)) {
		LOG.debug("RangerServiceDefHelper(): found delegate in cache with matching serviceName.  Need to check date");
		Delegate that = _Cache.get(serviceName);
		if (Objects.equals(that.getServiceFreshnessDate(), serviceDefFreshnessDate)) {
			delegate = that;
			LOG.debug("RangerServiceDefHelper(): cached delegate matched in date, too! Will use it now.");
		} else {
			LOG.debug("RangerServiceDefHelper(): cached delegate date mismatch!");
		}
	}
	if (delegate == null) { // either not found in cache or date didn't match
		delegate = new Delegate(serviceDef, checkForCycles);
		if (useCache) {
			LOG.debug("RangerServiceDefHelper(): Created new delegate and put in delegate cache!");
			_Cache.put(serviceName, delegate);
		}
	}
	_delegate = delegate;
}
 
Example 8
Source File: RangerServiceDefHelper.java    From ranger with Apache License 2.0 5 votes vote down vote up
public Delegate(RangerServiceDef serviceDef, boolean checkForCycles) {
	// NOTE: we assume serviceDef, its name and update time are can never by null.
	_serviceDef = serviceDef;
	_serviceName = serviceDef.getName();
	_serviceDefFreshnessDate = serviceDef.getUpdateTime();
	_checkForCycles = checkForCycles;

	boolean isValid = true;
	for(Integer policyType : RangerPolicy.POLICY_TYPES) {
		List<RangerResourceDef> resources = getResourceDefs(serviceDef, policyType);
		DirectedGraph graph = createGraph(resources);

		if(graph != null) {
			Map<String, RangerResourceDef> resourceDefMap = getResourcesAsMap(resources);
			if (isValid(graph, resourceDefMap)) {
				Set<List<RangerResourceDef>> hierarchies = getHierarchies(graph, resourceDefMap);
				_hierarchies.put(policyType, Collections.unmodifiableSet(hierarchies));
			} else {
				isValid = false;
				_hierarchies.put(policyType, EMPTY_RESOURCE_HIERARCHY);
			}
		} else {
			_hierarchies.put(policyType, EMPTY_RESOURCE_HIERARCHY);
		}
	}
	_valid = isValid;
	if (LOG.isDebugEnabled()) {
		String message = String.format("Found [%d] resource hierarchies for service [%s] update-date[%s]: %s", _hierarchies.size(), _serviceName,
				_serviceDefFreshnessDate == null ? null : _serviceDefFreshnessDate.toString(), _hierarchies);
		LOG.debug(message);
	}
}
 
Example 9
Source File: RangerDataHistService.java    From ranger with Apache License 2.0 4 votes vote down vote up
public void createObjectDataHistory(RangerBaseModelObject baseModelObj, String action) {
	if(baseModelObj == null || action == null) {
		throw restErrorUtil
				.createRESTException("Error while creating DataHistory. "
						+ "Object or Action can not be null.",
						MessageEnums.DATA_NOT_FOUND);
	}
	
	
	Integer classType = null;
	String objectName = null;
	String content = null;
	
	Long objectId = baseModelObj.getId();
	String objectGuid = baseModelObj.getGuid();
	Date currentDate = DateUtil.getUTCDate();
	
	XXDataHist xDataHist = new XXDataHist();
	
	xDataHist.setObjectId(baseModelObj.getId());
	xDataHist.setObjectGuid(objectGuid);
	xDataHist.setCreateTime(currentDate);
	xDataHist.setAction(action);
	xDataHist.setVersion(baseModelObj.getVersion());
	xDataHist.setUpdateTime(currentDate);
	xDataHist.setFromTime(currentDate);

	if(baseModelObj instanceof RangerServiceDef) {
		RangerServiceDef serviceDef = (RangerServiceDef) baseModelObj;
		objectName = serviceDef.getName();
		classType = AppConstants.CLASS_TYPE_XA_SERVICE_DEF;
		content = jsonUtil.writeObjectAsString(serviceDef);
	} else if(baseModelObj instanceof RangerService) {
		RangerService service = (RangerService) baseModelObj;
		objectName = service.getName();
		classType = AppConstants.CLASS_TYPE_XA_SERVICE;
		content = jsonUtil.writeObjectAsString(service);
	} else if(baseModelObj instanceof RangerPolicy) {
		RangerPolicy policy = (RangerPolicy) baseModelObj;
		objectName = policy.getName();
		classType = AppConstants.CLASS_TYPE_RANGER_POLICY;
		policy.setServiceType(policy.getServiceType());
		content = jsonUtil.writeObjectAsString(policy);
	}
	
	xDataHist.setObjectClassType(classType);
	xDataHist.setObjectName(objectName);
	xDataHist.setContent(content);
	xDataHist = daoMgr.getXXDataHist().create(xDataHist);
	
	if (ACTION_UPDATE.equalsIgnoreCase(action) || ACTION_DELETE.equalsIgnoreCase(action)) {
		XXDataHist prevHist = daoMgr.getXXDataHist().findLatestByObjectClassTypeAndObjectId(classType, objectId);
		
		if(prevHist == null) {
			throw restErrorUtil.createRESTException(
					"Error updating DataHistory Object. ObjectName: "
							+ objectName, MessageEnums.DATA_NOT_UPDATABLE);
		}
		
		prevHist.setUpdateTime(currentDate);
		prevHist.setToTime(currentDate);
		prevHist.setObjectName(objectName);
		prevHist = daoMgr.getXXDataHist().update(prevHist);
	}
}
 
Example 10
Source File: ServiceMgr.java    From ranger with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Class<RangerBaseService> getClassForServiceType(RangerServiceDef serviceDef) throws Exception {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> ServiceMgr.getClassForServiceType(" + serviceDef + ")");
	}

	Class<RangerBaseService> ret = null;

	if(serviceDef != null) {
		String serviceType = serviceDef.getName();

		ret = serviceTypeClassMap.get(serviceType);

		if(ret == null) {
			synchronized(serviceTypeClassMap) {
				ret = serviceTypeClassMap.get(serviceType);

				if(ret == null) {
					String clsName = serviceDef.getImplClass();

					if(LOG.isDebugEnabled()) {
						LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + clsName + " not found in cache");
					}
					try {

						Class<?> cls;

						if (StringUtils.isEmpty(clsName)) {
							if (LOG.isDebugEnabled()) {
								LOG.debug("No service-class configured for service-type:[" + serviceType + "], using RangerDefaultService");
							}
							clsName = RANGER_DEFAULT_SERVICE_NAME;

							cls = Class.forName(clsName);
						} else {
							URL[] pluginFiles = getPluginFilesForServiceType(serviceType);

							URLClassLoader clsLoader = new URLClassLoader(pluginFiles, Thread.currentThread().getContextClassLoader());

							cls = Class.forName(clsName, true, clsLoader);
						}

						ret = (Class<RangerBaseService>) cls;

						serviceTypeClassMap.put(serviceType, ret);

						if (LOG.isDebugEnabled()) {
							LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + clsName + " added to cache");
						}
					} catch (Exception excp) {
						LOG.warn("ServiceMgr.getClassForServiceType(" + serviceType + "): failed to find service-class '" + clsName + "'. Resource lookup will not be available", excp);
						//Let's propagate the error
						throw new Exception(serviceType + " failed to find service class " + clsName + ". Resource lookup will not be available. Please make sure plugin jar is in the correct place.");
					}
				} else {
					if(LOG.isDebugEnabled()) {
						LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + ret.getCanonicalName() + " found in cache");
					}
				}
			}
		} else {
			if(LOG.isDebugEnabled()) {
				LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + ret.getCanonicalName() + " found in cache");
			}
		}
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== ServiceMgr.getClassForServiceType(" + serviceDef + "): " + ret);
	}

	return ret;
}
 
Example 11
Source File: PolicyEngine.java    From ranger with Apache License 2.0 4 votes vote down vote up
public PolicyEngine cloneWithDelta(ServicePolicies servicePolicies) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> cloneWithDelta(" + Arrays.toString(servicePolicies.getPolicyDeltas().toArray()) + ", " + servicePolicies.getPolicyVersion() + ")");
    }

    final PolicyEngine ret;
    RangerPerfTracer   perf = null;

    if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_INIT_LOG)) {
        perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_INIT_LOG, "RangerPolicyEngine.cloneWithDelta()");
    }

    RangerServiceDef serviceDef    = this.getServiceDef();
    String           serviceType   = (serviceDef != null) ? serviceDef.getName() : "";
    boolean          isValidDeltas = false;

    if (CollectionUtils.isNotEmpty(servicePolicies.getPolicyDeltas()) || MapUtils.isNotEmpty(servicePolicies.getSecurityZones())) {
        isValidDeltas = CollectionUtils.isEmpty(servicePolicies.getPolicyDeltas()) || RangerPolicyDeltaUtil.isValidDeltas(servicePolicies.getPolicyDeltas(), serviceType);

        if (isValidDeltas) {
            if (MapUtils.isNotEmpty(servicePolicies.getSecurityZones())) {
                for (Map.Entry<String, ServicePolicies.SecurityZoneInfo> entry : servicePolicies.getSecurityZones().entrySet()) {
                    if (!RangerPolicyDeltaUtil.isValidDeltas(entry.getValue().getPolicyDeltas(), serviceType)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Invalid policy-deltas for security zone:[" + entry.getKey() + "]");
                        }

                        isValidDeltas = false;
                        break;
                    }
                }
            }
        }
    }

    if (isValidDeltas) {
        ret = new PolicyEngine(this, servicePolicies);
    } else {
        ret = null;
    }

    RangerPerfTracer.log(perf);

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== cloneWithDelta(" + Arrays.toString(servicePolicies.getPolicyDeltas().toArray()) + ", " + servicePolicies.getPolicyVersion() + ")");
    }
    return ret;
}
 
Example 12
Source File: RangerServiceDefHelper.java    From ranger with Apache License 2.0 3 votes vote down vote up
static public RangerServiceDef getServiceDefForPolicyFiltering(RangerServiceDef serviceDef) {

		List<RangerResourceDef> modifiedResourceDefs = new ArrayList<RangerResourceDef>();

		for (RangerResourceDef resourceDef : serviceDef.getResources()) {

			final RangerResourceDef modifiedResourceDef;

			String matcherClassName = resourceDef.getMatcher();

			if (RangerPathResourceMatcher.class.getName().equals(matcherClassName)) {

				Map<String, String> modifiedMatcherOptions = new HashMap<String, String>(resourceDef.getMatcherOptions());

				modifiedMatcherOptions.put(RangerAbstractResourceMatcher.OPTION_WILD_CARD, "false");

				modifiedResourceDef = new RangerResourceDef(resourceDef);
				modifiedResourceDef.setMatcherOptions(modifiedMatcherOptions);
				modifiedResourceDef.setRecursiveSupported(false);

			} else {
				modifiedResourceDef = resourceDef;
			}

			modifiedResourceDefs.add(modifiedResourceDef);
		}

		return new RangerServiceDef(serviceDef.getName(), serviceDef.getDisplayName(), serviceDef.getImplClass(), serviceDef.getLabel(),
				serviceDef.getDescription(), serviceDef.getOptions(), serviceDef.getConfigs(), modifiedResourceDefs, serviceDef.getAccessTypes(),
				serviceDef.getPolicyConditions(), serviceDef.getContextEnrichers(), serviceDef.getEnums());
	}