|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. 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, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | +package org.apache.cloudstack.tosca; |
| 18 | + |
| 19 | +import com.cloud.exception.InvalidParameterValueException; |
| 20 | +import org.apache.cloudstack.persistence.iactemplatesprofile.IacResourceTypeVO; |
| 21 | +import org.apache.cloudstack.tosca.model.ToscaNodeTemplate; |
| 22 | +import org.apache.cloudstack.tosca.model.ToscaNodeType; |
| 23 | +import org.apache.cloudstack.tosca.model.ToscaServiceTemplate; |
| 24 | +import org.apache.cloudstack.tosca.parser.ToscaParser; |
| 25 | +import org.apache.logging.log4j.LogManager; |
| 26 | +import org.apache.logging.log4j.Logger; |
| 27 | + |
| 28 | +import javax.inject.Inject; |
| 29 | +import java.util.ArrayList; |
| 30 | +import java.util.Collections; |
| 31 | +import java.util.HashMap; |
| 32 | +import java.util.HashSet; |
| 33 | +import java.util.List; |
| 34 | +import java.util.Map; |
| 35 | +import java.util.Set; |
| 36 | +import java.util.concurrent.CompletableFuture; |
| 37 | +import java.util.concurrent.CompletionException; |
| 38 | +import java.util.concurrent.ExecutorService; |
| 39 | +import java.util.concurrent.Executors; |
| 40 | +import java.util.stream.Collectors; |
| 41 | + |
| 42 | +public class ToscaOrchestrator { |
| 43 | + private final Logger logger = LogManager.getLogger(ToscaOrchestrator.class); |
| 44 | + |
| 45 | + @Inject |
| 46 | + private ToscaParser toscaParser; |
| 47 | + |
| 48 | + private Map<String, ToscaNodeType> toscaProfile; |
| 49 | + |
| 50 | + private ExecutorService executorPool; |
| 51 | + |
| 52 | + public void deployIacTemplate(String iacTemplateContent) { |
| 53 | + logger.debug("Parsing service template"); |
| 54 | + ToscaServiceTemplate serviceTemplate = toscaParser.parseServiceTemplate(iacTemplateContent, toscaProfile, null); |
| 55 | + Map<ToscaNodeTemplate, CompletableFuture<String>> provisioningTasksFutures = createProvisioningTasksFutures(serviceTemplate); |
| 56 | + CompletableFuture<Void> serviceTemplateFeature = CompletableFuture.allOf(provisioningTasksFutures.values().toArray(new CompletableFuture[0])); |
| 57 | + serviceTemplateFeature.join(); |
| 58 | + } |
| 59 | + |
| 60 | + private Map<ToscaNodeTemplate, CompletableFuture<String>> createProvisioningTasksFutures(ToscaServiceTemplate serviceTemplate) { |
| 61 | + logger.debug("Creating provisioning tasks futures"); |
| 62 | + Map<ToscaNodeTemplate, CompletableFuture<String>> futures = new HashMap<>(); |
| 63 | + Map<String, Set<ToscaNodeTemplate>> dependencyGraph = serviceTemplate.getDependencyGraph(); |
| 64 | + |
| 65 | + List<String> nodesWithoutDependencies = dependencyGraph.keySet().stream().filter(node -> dependencyGraph.get(node).isEmpty()).collect(Collectors.toList()); |
| 66 | + logger.debug("Nodes without dependencies: " + nodesWithoutDependencies); |
| 67 | + nodesWithoutDependencies.forEach(node -> { |
| 68 | + ToscaNodeTemplate nodeTemplate = serviceTemplate.getNodeTemplates().get(node); |
| 69 | + CompletableFuture<String> taskFuture = buildNodeProvisioningTask(nodeTemplate); |
| 70 | + futures.put(nodeTemplate, taskFuture); |
| 71 | + }); |
| 72 | + logger.debug("Built all the features for the nodes without dependencies."); |
| 73 | + |
| 74 | + logger.debug("Service template size: " + serviceTemplate.getNodeTemplates().size()); |
| 75 | + while (futures.size() < serviceTemplate.getNodeTemplates().size()) { |
| 76 | + logger.debug("Futures size: " + futures.size()); |
| 77 | + List<ToscaNodeTemplate> nodesWhoseDependenciesAlreadyHaveFutures = dependencyGraph.keySet().stream() |
| 78 | + .filter(node -> !dependencyGraph.get(node).isEmpty() && dependencyGraph.get(node).stream().allMatch(futures::containsKey)) |
| 79 | + .map(node -> serviceTemplate.getNodeTemplates().get(node)) |
| 80 | + .collect(Collectors.toList()); |
| 81 | + |
| 82 | + for (ToscaNodeTemplate node : nodesWhoseDependenciesAlreadyHaveFutures) { |
| 83 | + CompletableFuture<?>[] dependencies = dependencyGraph.get(node.getName()).stream().map(futures::get).toArray(CompletableFuture[]::new); |
| 84 | + CompletableFuture<String> taskFuture = CompletableFuture.allOf(dependencies).thenCompose(v -> { |
| 85 | + logger.debug("All dependencies of the node [" + node.getName() + "] are ready."); |
| 86 | + logger.debug("Here you'll be able to resolve the unresolved properties by get property and get attribute"); |
| 87 | + return buildNodeProvisioningTask(node); |
| 88 | + }); |
| 89 | + |
| 90 | + futures.put(node, taskFuture); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + return futures; |
| 95 | + } |
| 96 | + |
| 97 | + // O(|V|+|E|) |
| 98 | + private List<String> getServiceTemplateTopologicalSort(ToscaServiceTemplate serviceTemplate) { |
| 99 | + Set<String> visitedNodes = new HashSet<>(); |
| 100 | + Set<String> branchAncestors = new HashSet<>(); |
| 101 | + List<String> topologicalSort = new ArrayList<>(); |
| 102 | + for (ToscaNodeTemplate node : serviceTemplate.getNodeTemplates().values()) { |
| 103 | + if (!visitedNodes.contains(node.getName())) { |
| 104 | + depthFirstSearch(topologicalSort, node.getName(), serviceTemplate.getDependencyGraph(), branchAncestors, visitedNodes); |
| 105 | + } |
| 106 | + } |
| 107 | + return topologicalSort; |
| 108 | + } |
| 109 | + |
| 110 | + private void depthFirstSearch(List<String> topologicalSort, String node, Map<String, Set<ToscaNodeTemplate>> graph, Set<String> branchAncestors, Set<String> visitedNodes) { |
| 111 | + visitedNodes.add(node); |
| 112 | + branchAncestors.add(node); |
| 113 | + for (ToscaNodeTemplate dependency : graph.getOrDefault(node, Collections.emptySet())) { |
| 114 | + if (branchAncestors.contains(dependency.getName())) { |
| 115 | + throw new InvalidParameterValueException("Cycle detected in node dependency graph - this should have been caught during template validation"); |
| 116 | + } |
| 117 | + |
| 118 | + if (!visitedNodes.contains(dependency.getName())) { |
| 119 | + depthFirstSearch(topologicalSort, dependency.getName(), graph, branchAncestors, visitedNodes); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + branchAncestors.remove(node); |
| 124 | + topologicalSort.add(node); |
| 125 | + } |
| 126 | + |
| 127 | + private CompletableFuture<String> buildNodeProvisioningTask(ToscaNodeTemplate nodeTemplate) { |
| 128 | + logger.debug("Inside build node provisioning task for node: " + nodeTemplate.getName()); |
| 129 | + return provisionNode(nodeTemplate) |
| 130 | +// .orTimeout(5, TimeUnit.SECONDS) |
| 131 | + .thenApply(result -> { |
| 132 | + System.out.println("✔ SUCCESS " + nodeTemplate.getName()); |
| 133 | + return result; |
| 134 | + }).exceptionally(ex -> { |
| 135 | + System.out.println("✖ FAILURE " + nodeTemplate.getName() + " → " + ex); |
| 136 | + throw new CompletionException(ex); |
| 137 | + }); |
| 138 | + } |
| 139 | + |
| 140 | + private CompletableFuture<String> provisionNode(ToscaNodeTemplate nodeTemplate) { |
| 141 | + return CompletableFuture.supplyAsync(() -> { |
| 142 | + |
| 143 | + logger.debug("Submitting async job for " + nodeTemplate.getName() + " on " + Thread.currentThread().getName()); |
| 144 | + |
| 145 | + try { |
| 146 | + Thread.sleep(1500); |
| 147 | + } catch (InterruptedException e) { |
| 148 | + throw new RuntimeException(e); |
| 149 | + } |
| 150 | + |
| 151 | + logger.debug("Here you'll be able to populate the attributes"); |
| 152 | + return "res-" + nodeTemplate.getName(); |
| 153 | + |
| 154 | + }, executorPool); |
| 155 | + } |
| 156 | + |
| 157 | + public void configureExecutorPool(int poolSize) { |
| 158 | + logger.info("Configuring TOSCA's fixed executor thread pool with [{}] threads.", poolSize); |
| 159 | + executorPool = Executors.newFixedThreadPool(poolSize); |
| 160 | + } |
| 161 | + |
| 162 | + public void loadToscaProfile(List<IacResourceTypeVO> iacResourceTypes) { |
| 163 | + logger.info("Loading TOSCA's profile with the following resource types: {}", iacResourceTypes.stream().map(IacResourceTypeVO::getName).collect(Collectors.toList())); |
| 164 | + |
| 165 | + toscaProfile = iacResourceTypes.stream() |
| 166 | + .map(resourceType -> toscaParser.parseNodeTypeDefinitionFile(resourceType.getContent())) |
| 167 | + .collect(Collectors.toMap(ToscaNodeType::getName, nodeType -> nodeType)); |
| 168 | + } |
| 169 | + |
| 170 | + public void shutdownExecutorPool() { |
| 171 | + logger.info("Shutting down TOSCA's fixed executor thread pool."); |
| 172 | + if (executorPool != null) { |
| 173 | + executorPool.shutdown(); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + protected Map<String, ToscaNodeType> getToscaProfile() { |
| 178 | + return Collections.unmodifiableMap(toscaProfile); |
| 179 | + } |
| 180 | +} |
0 commit comments