Revert "Renaming Files having BluePrint to have Blueprint"
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / blueprints / resource-dict / src / main / kotlin / org / onap / ccsdk / cds / controllerblueprints / resource / dict / service / ResourceAssignmentValidationService.kt
1 /*
2  *  Copyright © 2017-2018 AT&T Intellectual Property.
3  *  Modifications Copyright © 2018 IBM.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.controllerblueprints.resource.dict.service
19
20 import org.apache.commons.collections.CollectionUtils
21 import org.apache.commons.lang3.StringUtils
22 import org.apache.commons.lang3.text.StrBuilder
23 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
24 import org.onap.ccsdk.cds.controllerblueprints.core.utils.TopologicalSortingUtils
25 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
26 import org.slf4j.LoggerFactory
27 import java.io.Serializable
28
29 /**
30  * ResourceAssignmentValidationService.
31  *
32  * @author Brinda Santh
33  */
34 interface ResourceAssignmentValidationService : Serializable {
35
36     @Throws(BluePrintException::class)
37     fun validate(resourceAssignments: List<ResourceAssignment>): Boolean
38 }
39
40 /**
41  * ResourceAssignmentValidationServiceImpl.
42  *
43  * @author Brinda Santh
44  */
45 open class ResourceAssignmentValidationServiceImpl : ResourceAssignmentValidationService {
46
47     private val log = LoggerFactory.getLogger(ResourceAssignmentValidationServiceImpl::class.java)
48
49     open var resourceAssignmentMap: Map<String, ResourceAssignment> = hashMapOf()
50     open val validationMessage = StrBuilder()
51
52     override fun validate(resourceAssignments: List<ResourceAssignment>): Boolean {
53         try {
54             validateTemplateNDictionaryKeys(resourceAssignments)
55             validateCyclicDependency(resourceAssignments)
56             if (StringUtils.isNotBlank(validationMessage)) {
57                 throw BluePrintException("Resource Assignment Validation Failure")
58             }
59         } catch (e: Exception) {
60             throw BluePrintException("Resource Assignment Validation :" + validationMessage.toString(), e)
61         }
62         return true
63     }
64
65     open fun validateTemplateNDictionaryKeys(resourceAssignments: List<ResourceAssignment>) {
66
67         resourceAssignmentMap = resourceAssignments.map { it.name to it }.toMap()
68
69         // Check the Resource Assignment has Duplicate Key Names
70         val duplicateKeyNames = resourceAssignments.groupBy { it.name }
71             .filter { it.value.size > 1 }
72             .map { it.key }
73
74         if (duplicateKeyNames.isNotEmpty()) {
75             validationMessage.appendln(String.format("Duplicate Assignment Template Keys (%s) is Present", duplicateKeyNames))
76         }
77
78         // Collect all the dependencies as a single list
79         val dependenciesNames = resourceAssignments.mapNotNull { it.dependencies }.flatten()
80
81         // Check all the dependencies keys have Resource Assignment mappings.
82         val notPresentDictionaries = dependenciesNames.filter { !resourceAssignmentMap.containsKey(it) }.distinct()
83         if (notPresentDictionaries.isNotEmpty()) {
84             validationMessage.appendln(String.format("No assignments for Dictionary Keys (%s)", notPresentDictionaries))
85         }
86
87         if (StringUtils.isNotBlank(validationMessage)) {
88             throw BluePrintException("Resource Assignment Validation Failure")
89         }
90     }
91
92     open fun validateCyclicDependency(resourceAssignments: List<ResourceAssignment>) {
93         val startResourceAssignment = ResourceAssignment()
94         startResourceAssignment.name = "*"
95
96         val topologySorting = TopologicalSortingUtils<ResourceAssignment>()
97
98         resourceAssignmentMap.map { it.value }.map { resourceAssignment ->
99             if (CollectionUtils.isNotEmpty(resourceAssignment.dependencies)) {
100                 resourceAssignment.dependencies!!.map {
101                     log.trace("Topological Graph link from {} to {}", it, resourceAssignment.name)
102                     topologySorting.add(resourceAssignmentMap[it]!!, resourceAssignment)
103                 }
104             } else {
105                 topologySorting.add(startResourceAssignment, resourceAssignment)
106             }
107         }
108
109         if (!topologySorting.isDag) {
110             val graph = getTopologicalGraph(topologySorting)
111             validationMessage.appendln("Cyclic Dependency :$graph")
112         }
113     }
114
115     open fun getTopologicalGraph(topologySorting: TopologicalSortingUtils<ResourceAssignment>): String {
116         val s = StringBuilder()
117         val neighbors = topologySorting.getNeighbors()
118
119         neighbors.forEach { v, vs ->
120             if (v.name == "*") {
121                 s.append("\n    * -> [")
122                 for (resourceAssignment in vs) {
123                     s.append(
124                         "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
125                             "),"
126                     )
127                 }
128                 s.append("]")
129             } else {
130                 s.append("\n    (" + v.dictionaryName + ":" + v.name + ") -> [")
131                 for (resourceAssignment in vs) {
132                     s.append(
133                         "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
134                             "),"
135                     )
136                 }
137                 s.append("]")
138             }
139         }
140         return s.toString()
141     }
142 }