12af030d548110245e6c19119a01a01a1a2a3302
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / impl / ActorImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actorserviceprovider.impl;
22
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.function.Function;
30 import org.onap.policy.common.parameters.BeanValidationResult;
31 import org.onap.policy.controlloop.actorserviceprovider.Operator;
32 import org.onap.policy.controlloop.actorserviceprovider.Util;
33 import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException;
34 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Implementation of an actor.
40  */
41 public class ActorImpl extends StartConfigPartial<Map<String, Object>> implements Actor {
42     private static final Logger logger = LoggerFactory.getLogger(ActorImpl.class);
43
44     /**
45      * Maps a name to an operator.
46      */
47     private final Map<String, Operator> name2operator = new ConcurrentHashMap<>();
48
49     /**
50      * Constructs the object.
51      *
52      * @param name actor name
53      */
54     public ActorImpl(String name) {
55         super(name);
56     }
57
58     /**
59      * This method simply returns {@code 0}.
60      */
61     @Override
62     public int getSequenceNumber() {
63         return 0;
64     }
65
66     /**
67      * Adds an operator supported by this actor.
68      *
69      * @param operator operation to be added
70      */
71     protected synchronized void addOperator(Operator operator) {
72         /*
73          * This method is "synchronized" to prevent the state from changing while the
74          * operator is added. The map, itself, does not need synchronization as it's a
75          * concurrent map.
76          */
77
78         if (isConfigured()) {
79             throw new IllegalStateException("attempt to set operators on a configured actor: " + getName());
80         }
81
82         name2operator.compute(operator.getName(), (opName, existingOp) -> {
83             if (existingOp == null) {
84                 return operator;
85             }
86
87             logger.warn("duplicate names for actor operation {}.{}: {}, ignoring {}", getName(), opName,
88                             existingOp.getClass().getSimpleName(), operator.getClass().getSimpleName());
89             return existingOp;
90         });
91     }
92
93     @Override
94     public String getName() {
95         return getFullName();
96     }
97
98     @Override
99     public Operator getOperator(String name) {
100         Operator operator = name2operator.get(name);
101         if (operator == null) {
102             throw new IllegalArgumentException("unknown operator " + getName() + "." + name);
103         }
104
105         return operator;
106     }
107
108     @Override
109     public Collection<Operator> getOperators() {
110         return name2operator.values();
111     }
112
113     @Override
114     public Set<String> getOperationNames() {
115         return name2operator.keySet();
116     }
117
118     /**
119      * For each operation, it looks for a set of parameters by the same name and, if
120      * found, configures the operation with the parameters.
121      */
122     @Override
123     protected void doConfigure(Map<String, Object> parameters) {
124         final String actorName = getName();
125         logger.info("configuring operations for actor {}", actorName);
126
127         BeanValidationResult valres = new BeanValidationResult(actorName, parameters);
128
129         // function that creates operator-specific parameters, given the operation name
130         Function<String, Map<String, Object>> opParamsMaker = makeOperatorParameters(parameters);
131
132         for (Operator operator : name2operator.values()) {
133             String operName = operator.getName();
134             Map<String, Object> subparams = opParamsMaker.apply(operName);
135
136             if (subparams != null) {
137
138                 try {
139                     operator.configure(subparams);
140
141                 } catch (ParameterValidationRuntimeException e) {
142                     logger.warn("failed to configure operation {}.{}", actorName, operName, e);
143                     valres.addResult(e.getResult());
144
145                 } catch (RuntimeException e) {
146                     logger.warn("failed to configure operation {}.{}", actorName, operName, e);
147                 }
148
149             } else if (operator.isConfigured()) {
150                 logger.warn("missing configuration parameters for operation {}.{}; using previous parameters",
151                                 actorName, operName);
152
153             } else {
154                 logger.warn("missing configuration parameters for operation {}.{}; operation cannot be started",
155                                 actorName, operName);
156             }
157         }
158     }
159
160     /**
161      * Extracts the operator parameters from the actor parameters, for a given operator.
162      * This method assumes each operation has its own set of parameters.
163      *
164      * @param actorParameters actor parameters
165      * @return a function to extract the operator parameters from the actor parameters.
166      *         Note: this function may return {@code null} if there are no parameters for
167      *         the given operation name
168      */
169     protected Function<String, Map<String, Object>> makeOperatorParameters(Map<String, Object> actorParameters) {
170
171         return operName -> Util.translateToMap(getName() + "." + operName, actorParameters.get(operName));
172     }
173
174     /**
175      * Starts each operation.
176      */
177     @Override
178     protected void doStart() {
179         final String actorName = getName();
180         logger.info("starting operations for actor {}", actorName);
181
182         for (Operator oper : name2operator.values()) {
183             if (oper.isConfigured()) {
184                 Util.runFunction(oper::start, "failed to start operation {}.{}", actorName, oper.getName());
185
186             } else {
187                 logger.warn("not starting unconfigured operation {}.{}", actorName, oper.getName());
188             }
189         }
190     }
191
192     /**
193      * Stops each operation.
194      */
195     @Override
196     protected void doStop() {
197         final String actorName = getName();
198         logger.info("stopping operations for actor {}", actorName);
199
200         // @formatter:off
201         name2operator.values().forEach(
202             oper -> Util.runFunction(oper::stop, "failed to stop operation {}.{}", actorName, oper.getName()));
203         // @formatter:on
204     }
205
206     /**
207      * Shuts down each operation.
208      */
209     @Override
210     protected void doShutdown() {
211         final String actorName = getName();
212         logger.info("shutting down operations for actor {}", actorName);
213
214         // @formatter:off
215         name2operator.values().forEach(oper -> Util.runFunction(oper::shutdown,
216                         "failed to shutdown operation {}.{}", actorName, oper.getName()));
217         // @formatter:on
218     }
219
220     // TODO old code: remove lines down to **HERE**
221
222     @Override
223     public String actor() {
224         return null;
225     }
226
227     @Override
228     public List<String> recipes() {
229         return Collections.emptyList();
230     }
231
232     @Override
233     public List<String> recipeTargets(String recipe) {
234         return Collections.emptyList();
235     }
236
237     @Override
238     public List<String> recipePayloads(String recipe) {
239         return Collections.emptyList();
240     }
241
242     // **HERE**
243 }