2886b1feb8f206ec4d2f242361355fca096501a9
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / ActorService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ActorService
4  * ================================================================================
5  * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actorserviceprovider;
23
24 import com.google.common.collect.ImmutableMap;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.ServiceLoader;
29 import java.util.Set;
30 import org.onap.policy.common.parameters.BeanValidationResult;
31 import org.onap.policy.controlloop.actorserviceprovider.impl.StartConfigPartial;
32 import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException;
33 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Service that manages a set of actors. To use the service, first invoke
39  * {@link #configure(Map)} to configure all of the actors, and then invoke
40  * {@link #start()} to start all of the actors. When finished using the actor service,
41  * invoke {@link #stop()} or {@link #shutdown()}.
42  */
43 public class ActorService extends StartConfigPartial<Map<String, Object>> {
44     private static final Logger logger = LoggerFactory.getLogger(ActorService.class);
45
46     private final Map<String, Actor> name2actor;
47
48     private static class LazyHolder {
49         static final ActorService INSTANCE = new ActorService();
50     }
51
52     /**
53      * Constructs the object and loads the list of actors.
54      */
55     protected ActorService() {
56         super("actors");
57
58         Map<String, Actor> map = new HashMap<>();
59
60         for (Actor newActor : loadActors()) {
61             map.compute(newActor.getName(), (name, existingActor) -> {
62                 if (existingActor == null) {
63                     return newActor;
64                 }
65
66                 logger.warn("duplicate actor names for {}: {}, ignoring {}", name,
67                                 existingActor.getClass().getSimpleName(), newActor.getClass().getSimpleName());
68                 return existingActor;
69             });
70         }
71
72         name2actor = ImmutableMap.copyOf(map);
73     }
74
75     /**
76      * Get the single instance.
77      *
78      * @return the instance
79      */
80     public static ActorService getInstance() {
81         return LazyHolder.INSTANCE;
82     }
83
84     /**
85      * Gets a particular actor.
86      *
87      * @param name name of the actor of interest
88      * @return the desired actor
89      * @throws IllegalArgumentException if no actor by the given name exists
90      */
91     public Actor getActor(String name) {
92         Actor actor = name2actor.get(name);
93         if (actor == null) {
94             throw new IllegalArgumentException("unknown actor " + name);
95         }
96
97         return actor;
98     }
99
100     /**
101      * Gets the actors.
102      *
103      * @return the actors
104      */
105     public Collection<Actor> getActors() {
106         return name2actor.values();
107     }
108
109     /**
110      * Gets the names of the actors.
111      *
112      * @return the actor names
113      */
114     public Set<String> getActorNames() {
115         return name2actor.keySet();
116     }
117
118     @Override
119     protected void doConfigure(Map<String, Object> parameters) {
120         logger.info("configuring actors");
121
122         BeanValidationResult valres = new BeanValidationResult("ActorService", parameters);
123
124         for (Actor actor : name2actor.values()) {
125             String actorName = actor.getName();
126             Map<String, Object> subparams = Util.translateToMap(actorName, parameters.get(actorName));
127
128             if (subparams != null) {
129
130                 try {
131                     actor.configure(subparams);
132
133                 } catch (ParameterValidationRuntimeException e) {
134                     logger.warn("failed to configure actor {}", actorName, e);
135                     valres.addResult(e.getResult());
136
137                 } catch (RuntimeException e) {
138                     logger.warn("failed to configure actor {}", actorName, e);
139                 }
140
141             } else if (actor.isConfigured()) {
142                 logger.warn("missing configuration parameters for actor {}; using previous parameters", actorName);
143
144             } else {
145                 logger.warn("missing configuration parameters for actor {}; actor cannot be started", actorName);
146             }
147         }
148
149         if (!valres.isValid() && logger.isWarnEnabled()) {
150             logger.warn("actor services validation errors:\n{}", valres.getResult());
151         }
152     }
153
154     @Override
155     protected void doStart() {
156         logger.info("starting actors");
157
158         for (Actor actor : name2actor.values()) {
159             if (actor.isConfigured()) {
160                 Util.runFunction(actor::start, "failed to start actor {}", actor.getName());
161
162             } else {
163                 logger.warn("not starting unconfigured actor {}", actor.getName());
164             }
165         }
166     }
167
168     @Override
169     protected void doStop() {
170         logger.info("stopping actors");
171         name2actor.values()
172                         .forEach(actor -> Util.runFunction(actor::stop, "failed to stop actor {}", actor.getName()));
173     }
174
175     @Override
176     protected void doShutdown() {
177         logger.info("shutting down actors");
178
179         // @formatter:off
180         name2actor.values().forEach(
181             actor -> Util.runFunction(actor::shutdown, "failed to shutdown actor {}", actor.getName()));
182
183         // @formatter:on
184     }
185
186     // the following methods may be overridden by junit tests
187
188     protected Iterable<Actor> loadActors() {
189         return ServiceLoader.load(Actor.class);
190     }
191 }