Java Code Examples for org.codehaus.jackson.node.ArrayNode#getElements()

The following examples show how to use org.codehaus.jackson.node.ArrayNode#getElements() . 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: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns the host url.
 * If the app is using path based routing, then path is appended to end of the host url 
 * @param specIngNode
 * @param healthCheckPort
 * @param isPathNeeded
 * @return
 */
private static String getHostUrlAndPath(JsonNode specIngNode, String healthCheckPort, boolean isPathNeeded) {
	// TODO Auto-generated method stub
	ArrayNode rulesArrayNode = (ArrayNode)specIngNode.get("rules");
   	Iterator<JsonNode> rulesNodeItr = rulesArrayNode.getElements();
   	while(rulesNodeItr.hasNext()){
   		JsonNode rulesNode = rulesNodeItr.next();
   		JsonNode hostNode = rulesNode.get("host");
   		if(hostNode == null){
   			return null;
   		}
   		String host = hostNode.asText();
   		if(!isPathNeeded){
   			return host;
   		}
   		JsonNode httpRuleNode = rulesNode.get("http");
   		ArrayNode pathsArrayNode = (ArrayNode)httpRuleNode.get("paths");
   		Iterator<JsonNode> pathsNodeItr = pathsArrayNode.getElements();
   		while(pathsNodeItr.hasNext()){
   			JsonNode pathsRootNode = pathsNodeItr.next();
   			JsonNode backendNode = pathsRootNode.get("backend");
   			JsonNode servicePortNode = backendNode.get("servicePort");
   			if(servicePortNode.asText().equals(healthCheckPort)){
   				JsonNode pathNode = pathsRootNode.get("path");
   				return host+pathNode.getTextValue();
   			}
   		}
   	}
   	return null;
}
 
Example 2
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns a Map with key as service name and value as Map with all selector values
 * @param authToken
 * @param eVo
 * @return
 * @throws Exception
 */
private static Map<String, Map<String, String>> getServiceLabelValues(String authToken, EnvironmentVO eVo) throws Exception {
	// TODO Auto-generated method stub
	String serviceApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_SERVICE_PATH);
	String serviceJson = RestCommunicationHandler.getResponse(serviceApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNodeServ = mapper.readTree(serviceJson);
	ArrayNode serviceNode = (ArrayNode) rootNodeServ.get("items");
	if(serviceNode == null || serviceNode.size() == 0){
		logger.info("No Service is available for the environment : "+eVo.getEnvironmentName());
		return null;
	}
	Map<String, Map<String, String>> serviceLabelMap = new HashMap<String, Map<String, String>>(); 
	Iterator<JsonNode> serviceIterator = serviceNode.getElements();
	while (serviceIterator.hasNext()) {
		JsonNode appsInNode = serviceIterator.next();
		JsonNode servMetadataNode = appsInNode.get("metadata");
		JsonNode servNameNode = servMetadataNode.get("name");
		String serviceName = servNameNode.getValueAsText();
		JsonNode namespaceNode = servMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding service - " + serviceName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> selectorMap = mapper.convertValue(selectorNode, Map.class);
		serviceLabelMap.put(namespace+"/"+serviceName, selectorMap);
	}
	return serviceLabelMap;
}
 
Example 3
Source File: WorkflowAccessor.java    From helix with Apache License 2.0 5 votes vote down vote up
private Map<String, JobConfig.Builder> getJobConfigs(ArrayNode root)
    throws HelixException, IOException {
  Map<String, JobConfig.Builder> jobConfigsMap = new HashMap<>();
  for (Iterator<JsonNode> it = root.getElements(); it.hasNext(); ) {
    JsonNode job = it.next();
    ZNRecord record = null;

    try {
      record = toZNRecord(job.toString());
    } catch (IOException e) {
      // Ignore the parse since it could be just simple fields
    }

    if (record == null || record.getSimpleFields().isEmpty()) {
      Map<String, String> cfgMap = OBJECT_MAPPER.readValue(job.toString(),
          TypeFactory.defaultInstance()
              .constructMapType(HashMap.class, String.class, String.class));
      jobConfigsMap
          .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(cfgMap));
    } else {
      jobConfigsMap
          .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(record));
    }
  }

  return jobConfigsMap;
}
 
Example 4
Source File: JsonUtil.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
public static List<String> getStrings(JsonNode node, String prop, List<String> defaultValue) throws JsonFormatException {
    ArrayNode arrayNode = getArray(node, prop, null);
    if (arrayNode == null) {
        return defaultValue;
    }
    List<String> elements = new ArrayList<String>();
    Iterator<JsonNode> elementItr = arrayNode.getElements();
    while (elementItr.hasNext()) {
        elements.add(elementItr.next().getValueAsText());
    }
    return elements;
}
 
Example 5
Source File: DefaultSelectorStore.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the specified resource file and returns a map of Strings to selectors. Selectors
 * are just maps of Strings to true/false.
 *
 * @param filename resource JSON file to load containing an array of type/selector docs
 * @return a map of the parsed file
 * @throws IOException
 * @throws SelectorParseException
 */
protected Map<String, SemanticSelector> readDefaultSelectorsFromFile(String filename) throws IOException, SelectorParseException {

    String fileAsString = IOUtils.toString(super.getClass().getResourceAsStream(filename));

    SelectionConverter selectionConverter = new Selector2MapOfMaps(false);

    Map<String, SemanticSelector> retVal = new HashMap<String, SemanticSelector>();

    ObjectMapper mapper = new ObjectMapper();
    JsonNode element = mapper.readValue(fileAsString, JsonNode.class);
    if (element instanceof ArrayNode) {
        ArrayNode arrayNode = (ArrayNode) element;
        Iterator<JsonNode> jsonNodeIterator = arrayNode.getElements();
        while (jsonNodeIterator.hasNext()) {
            JsonNode jsonNode = jsonNodeIterator.next();
            try {
                String type = jsonNode.get(DEFAULT_SELECTOR_TYPE_KEY).getTextValue();
                String selectorString = jsonNode.get(DEFAULT_SELECTOR_VALUE_KEY).getTextValue();

                ClassType classType = modelProvider.getClassType(type);
                SemanticSelector semanticSelector = selectorSemanticModel.parse(selectionConverter.convert(selectorString), classType);

                retVal.put(type, semanticSelector);
            } catch (IllegalArgumentException npe) {
                LOG.warn("Default selector entry missing 'type' or 'selector' field(s): " + jsonNode.toString());
            } catch (SelectorParseException spe) {
                LOG.warn("Default selector failed to parse: " + spe.getMessage());
            }
        }
    }

    return retVal;
}
 
Example 6
Source File: GenericEntityDeserializer.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private List<Object> processArray(final String key, final ArrayNode asJsonArray) {
    List<Object> list = new LinkedList<Object>();
    
    Iterator<JsonNode> it = asJsonArray.getElements();
    while (it.hasNext()) {
        list.add(processElement(key, it.next()));
    }
    return list;
}
 
Example 7
Source File: MarathonConfigProcessor.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
    * Function to update component table from marathon config 
    * @param json Marathon config JSON
    * @param environmentId environment Id
    * @throws JsonProcesssingException
    * @throws IOException
    * @throws SQLException
    */
   @SuppressWarnings("deprecation")
public static void updateComponentFromMarathonConfig(String json, int environmentId, long regionId) throws SQLException, JsonProcessingException, IOException{
       logger.debug("Getting API's from Marathon configuration and posting to DB. environmentId = " + environmentId);

       List<ComponentVO> oldAPIComponentVOs = DBQueryUtil.getAllAPIComponentDetails(environmentId, SurveillerConstants.MESOS_PLATFORM, regionId);
       List<ComponentVO> newAPIComponentVOs = new ArrayList<ComponentVO>();
       List<HealthCheckVO> statusChangedList = new ArrayList<HealthCheckVO>();
       ObjectMapper mapper = new ObjectMapper();
       JsonNode rootNode = mapper.readTree(json);
       ArrayNode appsNode = (ArrayNode) rootNode.get("apps");
       Iterator<JsonNode> appsIterator = appsNode.getElements();
       while (appsIterator.hasNext()) {
           JsonNode appsInNode = appsIterator.next();
           JsonNode id = appsInNode.get("id");
           String idStr = id.getValueAsText();
           String idSubStr = idStr.substring(id.getValueAsText().indexOf('/') + 1);
           if(idSubStr.indexOf('/')  < 0){
               logger.info("Unable to process App Id : " + idStr);
               continue;
           }
           String appName = idSubStr.substring(0, idSubStr.indexOf('/'));
           String apiName = idSubStr.substring(idSubStr.indexOf('/')+1);
           
           Integer tasksRunning = appsInNode.get(SurveillerConstants.NUM_OF_TASKS_RUNNING) == null ? null : appsInNode.get(SurveillerConstants.NUM_OF_TASKS_RUNNING).getIntValue();
           Integer tasksStaged = appsInNode.get(SurveillerConstants.NUM_OF_TASKS_RUNNING) == null ? null : appsInNode.get(SurveillerConstants.NUM_OF_TASKS_STAGED).getIntValue();
           
           if(tasksRunning != null && tasksRunning.intValue() == 0 && tasksStaged != null && tasksStaged.intValue() == 0){
           	continue;
           }
           
           JsonNode lblNode = appsInNode.get("labels");
           int apiId = 0;
           if(lblNode != null && lblNode.get("HEALTHCHECK") != null){
               String healthCheckUrl = lblNode.get("HEALTHCHECK").getTextValue();
               if(healthCheckUrl != null && !healthCheckUrl.trim().equals("")){
                   apiId = DBQueryUtil.checkAndInsertComponent(appName, apiName, ComponentType.APP, healthCheckUrl, environmentId,
                   		regionId, HealthCheckType.URL_200_CHECK, SurveillerConstants.MESOS_PLATFORM);
               }
           }
           // Case in which there is no health check URL configure inside label
           // Mark as Warning if there is atleast one unhealthy task
           // Mark as Down if all tasks are unhealthy
           if(apiId == 0){
           	Integer tasksUnhealthy = appsInNode.get("tasksUnhealthy") == null ? null : appsInNode.get("tasksUnhealthy").getIntValue();
               if(tasksRunning != null && tasksUnhealthy != null && tasksRunning.intValue() != 0){
                   Status status = Status.UP;
                   if(tasksRunning.equals(tasksUnhealthy) ){
                       status = Status.DOWN;
                   }else if(tasksUnhealthy.intValue() != 0){
                       status = Status.WARNING;
                   }
                   apiId = DBQueryUtil.checkAndInsertComponent(appName, apiName, ComponentType.APP, null, environmentId,
                   		regionId, HealthCheckType.DUMMY, SurveillerConstants.MESOS_PLATFORM);
                   String marathonMessage = "Marathon Status - Running Tasks = " + tasksRunning + "; UnHealthy Task = " + tasksUnhealthy;
                   boolean isStatusChanged = DBQueryUtil.checkAndUpdateMessage(apiId,environmentId,regionId, HealthCheckType.DUMMY,status,marathonMessage);
                   if(isStatusChanged){
                   	statusChangedList.add(createVoWithComponentDetails(apiId,environmentId,regionId,status,marathonMessage));
                   }
                   DBQueryUtil.updateMarathonHealthCheckStatus(apiId,environmentId,regionId, HealthCheckType.DUMMY,status, isStatusChanged);
               }
           }
           if(apiId != 0){
               newAPIComponentVOs.add(DBQueryUtil.getComponent(apiId));
           }
       }
       compareAPILists(oldAPIComponentVOs, newAPIComponentVOs, environmentId, regionId);
       if(statusChangedList.size() > 0){
       	CommonsUtil.sendMailForChangedStatus(statusChangedList);
       }
   }
 
Example 8
Source File: K8sAPIDashboardTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
 * Method to get all Pods and Containers associated to the deployment.
 * 
 * @param authToken
 * @param eVo
 * @param depLabelMap
 * @param externalPodsMap
 *
 */
private static void getPodsAndContainersOfDeployments(String authToken, EnvironmentVO eVo,
		Map<String, List<ServiceLabelVO>> depLabelMap, Map<String, ArrayList<Integer>> externalPodsMap) throws IOException {
	String podApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_PODS_PATH);
	/* Call - the Kube Pod api to get all the Pods in the Cluster */
	String podJson = RestCommunicationHandler.getResponse(podApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode podRootNode = mapper.readTree(podJson);
	ArrayNode appsNode = (ArrayNode) podRootNode.get("items");
	Iterator<JsonNode> podsIterator = appsNode.getElements();
	while (podsIterator.hasNext()) {
		JsonNode appsInNode = podsIterator.next();
		JsonNode metadataNode = appsInNode.get("metadata");
		JsonNode nameNode = metadataNode.get("name");
		String podName = nameNode.getValueAsText();
		JsonNode namespaceNode = metadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding Pods - " + podName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode specNode = appsInNode.get("spec");
		ArrayNode contArrayNode = (ArrayNode) specNode.get("containers");
		/* Number of containers in Pod */
		int numCount = contArrayNode.size();
		//JsonNode ownerReferencesNode = 
		ArrayNode ownerReferencesArray = (ArrayNode) metadataNode.get("ownerReferences");
		if(ownerReferencesArray == null){
			loadPodsAndContainer("Kube-Systems",namespace, externalPodsMap, numCount);
			continue;
		}
		JsonNode ownerReferencesNode = ownerReferencesArray.get(0);
		JsonNode kindNode = ownerReferencesNode.get("kind");
		String kind = kindNode.getTextValue();
		if(!kind.equalsIgnoreCase("ReplicaSet")){
			loadPodsAndContainer(kind,namespace , externalPodsMap, numCount);
			continue;
		}
		
		JsonNode labelsNode = metadataNode.get("labels");
		if (labelsNode == null) {
			logger.info("The labelsNode is null for the pod - " + podName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> podLabelMap = mapper.convertValue(labelsNode, Map.class);
		List<ServiceLabelVO> servLblList = depLabelMap.get(namespace);
		if(servLblList == null){
			continue;
		}
		serviceLabelLoop: for (ServiceLabelVO servLabelVo : servLblList) {
			int labelCount = 0;
			for (Entry<String, String> labelInfo : servLabelVo.getLabel().entrySet()) {
				if (podLabelMap.containsKey(labelInfo.getKey())) {
					if (podLabelMap.get(labelInfo.getKey()).equals(labelInfo.getValue())) {
						labelCount = labelCount + 1;
					} else {
						continue serviceLabelLoop;
					}
				} else {
					continue serviceLabelLoop;
				}
			}
			if (servLabelVo.getLabel().size() == labelCount) {
				
				servLabelVo.setNumOfContainers(servLabelVo.getNumOfContainers() + numCount);
				servLabelVo.setNumOfPods(servLabelVo.getNumOfPods() + 1);
				break;
			}
		}
	}
	
}
 
Example 9
Source File: K8sAPIDashboardTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
 * Method to get all Deployment and MatchLabels of the given cluster
 * 
 * @param authToken
 * @param eVo
 * @param depLabelMap
 *
 */
private static void getDeploymentAndMatchLabels(String authToken, EnvironmentVO eVo, Map<String, List<ServiceLabelVO>> depLabelMap) throws IOException {

	String deployementApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_DEPLOYMENT_PATH);
	String deploymentJson = RestCommunicationHandler.getResponse(deployementApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNode = mapper.readTree(deploymentJson);
	ArrayNode deploymentNode = (ArrayNode) rootNode.get("items");
	if (deploymentNode.size() == 0) {
		String errorString = "Surveiller task DOK8SAPIDASHBOARDTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Deployment JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	
	Iterator<JsonNode> deploymentIterator = deploymentNode.getElements();
	while (deploymentIterator.hasNext()) {
		JsonNode appsInNode = deploymentIterator.next();
		JsonNode depMetadataNode = appsInNode.get("metadata");
		JsonNode depNameNode = depMetadataNode.get("name");
		String depName = depNameNode.getValueAsText();
		JsonNode namespaceNode = depMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding deployment - " + depName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode matchLabelsNode = selectorNode.get("matchLabels");
		if (matchLabelsNode == null) {
			logger.info("The matchLabelsNode is null for the deployment - " + depName + " in the namespace - "
					+ namespace);
			continue;
		}
		Map<String, String> labelMap = mapper.convertValue(matchLabelsNode, Map.class);
		ServiceLabelVO slVo = new ServiceLabelVO();
		slVo.setLabel(labelMap);
		String serviceName = namespace + "/" + depName;
		slVo.setServiceName(serviceName);
		String appName = namespace.substring(0, namespace.indexOf("-"));
		slVo.setAppName(appName);
		List<ServiceLabelVO> servLblList = null;
		if (depLabelMap.containsKey(namespace)) {
			servLblList = depLabelMap.get(namespace);
		} else {
			servLblList = new ArrayList<ServiceLabelVO>();
		}
		servLblList.add(slVo);
		depLabelMap.put(namespace, servLblList);
		
	}
}
 
Example 10
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**
 * The function returns all Ingress as a Map, with key as service name & Ingress root node
 * @param ingressJson
 * @param eVo
 * @return
 * @throws Exception 
 */
private static Map<String, JsonNode> getIngressLookupMap(String authToken, EnvironmentVO eVo) throws Exception {
	// TODO Auto-generated method stub
	String ingressApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_INGRESS_PATH);
	String ingressJson = RestCommunicationHandler.getResponse(ingressApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode ingRootNode = mapper.readTree(ingressJson);
       ArrayNode ingressArrayNode = (ArrayNode) ingRootNode.get("items");
       if(ingressArrayNode == null || ingressArrayNode.size() == 0){
       	logger.info("No Ingress is available for the environment : "+eVo.getEnvironmentName());
		return null;
       }
       Iterator<JsonNode> ingressIterator = ingressArrayNode.getElements();
       Map<String, JsonNode> ingressMap = new HashMap<String, JsonNode>();
       while (ingressIterator.hasNext()) {
       	
       	JsonNode ingressInNode = ingressIterator.next();
       	JsonNode metadataNode = ingressInNode.get("metadata");
       	JsonNode nameNode = metadataNode.get("name");
       	String ingressName = nameNode.getValueAsText();
       	JsonNode namespaceNode = metadataNode.get("namespace");
       	String namespace = namespaceNode.getValueAsText();
       	if (!namespace.contains("-")) {
			logger.info("Excluding Ingress - " + ingressName + " in the namespace - " + namespace);
			continue;
		}
       	/*This particular block of code is to avoid code executions for the applications with multiple ingress
       	 * FIXME: Remove if this logic is not necessary
       	 * CASE: Services with multiple Ingress 
       	 * In our case the annotation "kubernetes.io/ingress.class" contains values "nginx-internal" or "nginx-external"
       	 * */
       	JsonNode annotNode = metadataNode.get("annotations");
       	if(annotNode == null){
       		logger.info("The annotations node is null for the Ingress - "+ingressName+" in the namespace - "+ namespace);
       	}else{
	        JsonNode ingClasstNode = annotNode.get("kubernetes.io/ingress.class");
            if(ingClasstNode == null || !ingClasstNode.getTextValue().equals("nginx-internal")){
            	logger.info("The hostname node is "+ingClasstNode+ "for the Ingress - "+ingressName+" in the namespace - "+ namespace);
            	continue;
            }
       	}   
           /******/
       	JsonNode specNode = ingressInNode.get("spec");
           if (specNode == null) {
			logger.info("The specNode is null for the ingress - " + ingressName + " in the namespace - "+ namespace);
			continue;
		}
           String serviceName = null;
           ArrayNode ruleArrayNode = (ArrayNode)specNode.get("rules");
           Iterator<JsonNode> ruleNodeItr = ruleArrayNode.getElements();
           while (ruleNodeItr.hasNext()) {
               JsonNode ruleNode = ruleNodeItr.next();
               JsonNode httpNode = ruleNode.get("http");
               if(httpNode == null){
               	logger.info("The httpNode is null for the ingress - " + ingressName + " in the namespace - "+ namespace);
               	continue;
               }
               ArrayNode pathArrayNode = (ArrayNode)httpNode.get("paths");
               Iterator<JsonNode> pathNodeItr = pathArrayNode.getElements();
               while (pathNodeItr.hasNext()) {
                JsonNode pathNode = pathNodeItr.next();
                JsonNode backendNode = pathNode.get("backend");
                JsonNode serviceNode = backendNode.get("serviceName");
                if (serviceNode == null) {
					logger.info("The serviceNode is null for the ingress - " + ingressName + " in the namespace - "+ namespace);
					continue;
				}
                serviceName = serviceNode.getTextValue();
                ingressMap.put(namespace+"/"+serviceName, ingressInNode);
               }    
          }	
       }
	return ingressMap;
}
 
Example 11
Source File: TPSLookupTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
private static Map<String, String> getAppService(EnvironmentVO eVo, String authToken) throws Exception {
	// TODO Auto-generated method stub
	
    /*Method to get All the deployment and the match label associated to each deployment.
     * The method will return a Map with namespace as key and value List<ServiceLabelVO>
     * */
	Map<String, List<ServiceLabelVO>> depLabelMap = getDepServiceLabel(eVo, authToken);
	/*Service Lookup Code*/
	
	String serviceApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_SERVICE_PATH);
	String serviceJson = RestCommunicationHandler.getResponse(serviceApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNodeServ = mapper.readTree(serviceJson);
	ArrayNode serviceNode = (ArrayNode) rootNodeServ.get("items");
	if (serviceNode.size() == 0) {
		String errorString = "Surveiller task DOK8STPSLOOKUPLOADTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Service JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	Map<String, String> appServiceMap = new HashMap<String, String>(); 
	Iterator<JsonNode> serviceIterator = serviceNode.getElements();
	while (serviceIterator.hasNext()) {
		JsonNode appsInNode = serviceIterator.next();
		JsonNode servMetadataNode = appsInNode.get("metadata");
		JsonNode servNameNode = servMetadataNode.get("name");
		String serviceName = servNameNode.getValueAsText();
		JsonNode namespaceNode = servMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding service - " + serviceName + " in the namespace - " + namespace);
			continue;
		}
		Map<String, String> selectorMap = mapper.convertValue(selectorNode, Map.class);
		List<ServiceLabelVO> servLblList = depLabelMap.get(namespace);
		if(servLblList == null){
			continue;
		}
		for(ServiceLabelVO servLabelVo : servLblList){
			if(servLabelVo.getLabel() == null){
				continue;
			}
			if(servLabelVo.getLabel().equals(selectorMap)){
				appServiceMap.put(serviceName, servLabelVo.getServiceName());
			}
		}
	}	
	return appServiceMap;
}
 
Example 12
Source File: TPSLookupTask.java    From kardio with Apache License 2.0 4 votes vote down vote up
/**Method to get All the deployment and the match label associated to each deployment.
 * @param eVo
 * @param authToken
 * @return
 * @throws Exception
 */
private static Map<String, List<ServiceLabelVO>> getDepServiceLabel(EnvironmentVO eVo, String authToken) throws Exception {
	String deployementApiUrl = eVo.getK8sUrl() + PropertyUtil.getInstance().getValue(SurveillerConstants.K8S_API_DEPLOYMENT_PATH);
	String deploymentJson = RestCommunicationHandler.getResponse(deployementApiUrl, true, SurveillerConstants.BEARER_TOKEN, authToken);
	ObjectMapper mapper = new ObjectMapper();
	JsonNode rootNode = mapper.readTree(deploymentJson);
	ArrayNode deploymentNode = (ArrayNode) rootNode.get("items");
	if (deploymentNode.size() == 0) {
		String errorString = "Surveiller task DOK8STPSLOOKUPLOADTASK - FAILED : Enviroment -"
				+ eVo.getEnvironmentName() + " Deployment JSON Cannot be empty";
		logger.error(errorString);
		throw new GeneralException(errorString);
	}
	Map<String, List<ServiceLabelVO>> depLabelMap = new HashMap<String, List<ServiceLabelVO>>();
	Iterator<JsonNode> deploymentIterator = deploymentNode.getElements();
	while (deploymentIterator.hasNext()) {
		JsonNode appsInNode = deploymentIterator.next();
		JsonNode depMetadataNode = appsInNode.get("metadata");
		JsonNode depNameNode = depMetadataNode.get("name");
		String depName = depNameNode.getValueAsText();
		JsonNode namespaceNode = depMetadataNode.get("namespace");
		String namespace = namespaceNode.getValueAsText();
		JsonNode specNode = appsInNode.get("spec");
		JsonNode selectorNode = specNode.get("selector");
		if (namespace.equals("default") || !namespace.contains("-")) {
			logger.info("Excluding deployment - " + depName + " in the namespace - " + namespace);
			continue;
		}
		JsonNode matchLabelsNode = selectorNode.get("matchLabels");
		if(matchLabelsNode == null) {
			logger.info("The matchLabelsNode is null for the deployment - " + depName + " in the namespace - "
					+ namespace);
			continue;
		}
		Map<String, String> labelMap = mapper.convertValue(matchLabelsNode, Map.class);
		ServiceLabelVO slVo = new ServiceLabelVO();
		slVo.setLabel(labelMap);
		String serviceName = namespace + "/" + depName;
		slVo.setServiceName(serviceName);
		String appName = namespace.substring(0, namespace.indexOf("-"));
		slVo.setAppName(appName);
		List<ServiceLabelVO> servLblList = null;
		if (depLabelMap.containsKey(namespace)) {
			servLblList = depLabelMap.get(namespace);
		} else {
			servLblList = new ArrayList<ServiceLabelVO>();
		}
		servLblList.add(slVo);
		depLabelMap.put(namespace, servLblList);
	}
	return depLabelMap;
}