2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.openecomp.appc.client.impl.core;
27 import org.openecomp.appc.client.impl.protocol.*;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
31 import java.util.Properties;
32 import java.util.concurrent.atomic.AtomicBoolean;
35 * Consolidates all services(Registry, Timeout and Task Queue) for handling of requests/responses events.
39 private final EELFLogger LOG = EELFManager.getInstance().getLogger(CoreManager.class);
40 private final ProtocolFactory protocolFactory;
41 protected AsyncProtocol protocol;
42 private final RetrieveMessageCallback protocolCallback = null;
43 private final CoreRegistry registry;
44 private final ITimerService timerService;
45 private final TaskQueueManager queueManager;
46 private String DEFAULT_TIMEOUT = "300000";
47 private final static String RESPONSE_TIMEOUT = "client.response.timeout";
48 private final static String GRACEFUL_SHUTDOWN_TIMEOUT = "client.graceful.shutdown.timeout";
49 private boolean isForceShutdown = false;
50 private AtomicBoolean isGracefulShutdown = new AtomicBoolean(false);
51 private long shutdownTimeout;
53 CoreManager(Properties prop) throws CoreException {
54 protocolFactory = ProtocolFactory.getInstance();
57 }catch (ProtocolException e){
58 throw new CoreException(e);
60 registry = new CoreRegistry<RequestResponseHandler>(new EmptyRegistryCallbackImpl());
61 String timeoutProp = prop.getProperty(RESPONSE_TIMEOUT, DEFAULT_TIMEOUT);
62 long responseTimeout = Long.parseLong(timeoutProp);
63 String gracefulTimeout = prop.getProperty(GRACEFUL_SHUTDOWN_TIMEOUT, DEFAULT_TIMEOUT);
64 shutdownTimeout = Long.parseLong(gracefulTimeout);
65 timerService = new TimerServiceImpl(responseTimeout);
66 queueManager = new TaskQueueManager(prop);
71 * initiates protocol layer services.
72 * @param prop - Properties
74 private void initProtocol(Properties prop) throws ProtocolException {
75 protocol = (AsyncProtocol) protocolFactory.getProtocolObject(ProtocolType.ASYNC);
76 protocol.init(prop, getProtocolCallback());
80 * Creates protocol response callback
81 * @return - @{@link ProtocolResponseCallbackImpl}
83 RetrieveMessageCallback getProtocolCallback(){
84 return new ProtocolResponseCallbackImpl();
88 * Registers a new handler in registry
89 * @param corrID - Correlation ID
90 * @param requestResponseHandler handler to be called when response arrives
92 void registerHandler(String corrID, RequestResponseHandler requestResponseHandler){
93 registry.register(corrID, requestResponseHandler);
97 * Remove a handler from registry service by correlation ID.
98 * @param corrID - Correlation ID
99 * @return - @{@link RequestResponseHandler}
101 RequestResponseHandler unregisterHandler(String corrID){
102 return (RequestResponseHandler) registry.unregister(corrID);
106 * Checks in registry service if a handler is existing.
107 * @param corrID - Correlation ID
110 boolean isExistHandler(String corrID) {
111 return registry.isExist(corrID);
115 * Starts timer for timeout event when a request was send successfully.
116 * @param corrID - Correlation ID
118 void startTimer(String corrID){
119 timerService.add(corrID, new TimeoutHandlerImpl(corrID));
123 * Cancels timer for fimeout event, in case when complete response was received
126 void cancelTimer(String corrID){
127 timerService.cancel(corrID);
131 * Submits a new task to Queue manager. it is using for both response and timeout tasks
132 * @param corrID - Correlation ID
133 * @param task - @{@link Runnable} task.
134 * @throws InterruptedException
136 void submitTask(String corrID, Runnable task) throws InterruptedException {
137 queueManager.submit(corrID, task);
141 * Sends request to protocol.
142 * @param request - Request
143 * @param corrId - Correlation ID
144 * @param rpcName - RPC name
145 * @throws CoreException - @{@link CoreException}
147 void sendRequest(String request, String corrId, String rpcName) throws CoreException {
148 MessageContext ctx = getMessageContext(corrId, rpcName);
150 protocol.sendRequest(request, ctx);
151 } catch (ProtocolException e) {
152 unregisterHandler(corrId);
153 throw new CoreException(e);
158 * Creates @{@link MessageContext}
159 * @param correlationId - Correlation ID
160 * @param rpcName - RPC Name
161 * @return - @{@link MessageContext}
163 private MessageContext getMessageContext(String correlationId, String rpcName){
164 MessageContext msgCtx = new MessageContext();
165 msgCtx.setCorrelationID(correlationId);
166 msgCtx.setRpc(rpcName);
171 * Implements response callback from protocol and filters responses by correlation ID.
172 * Only registered events(by correlation ID) will be handled.
174 private class ProtocolResponseCallbackImpl implements RetrieveMessageCallback {
176 public void onResponse(String response, MessageContext context) {
177 String corrID = context.getCorrelationID();
178 if (corrID != null) {
179 RequestResponseHandler messageHandler = (RequestResponseHandler) registry.get(corrID);
180 if (messageHandler != null) {
181 LOG.info("On response callback corrID <" + corrID + "> handler " + messageHandler + " response " + response);
182 messageHandler.handleResponse(context, response);
190 * listens to @{@link Runtime} shutdown event
192 private void listenShutdown() {
193 Runtime.getRuntime().addShutdownHook(new Thread(){
201 * Implements shutdown for client library.
202 * @param isForceShutdown - true force shutdown, false graceful shutdown
204 void shutdown(boolean isForceShutdown){
213 * Graceful shutdown. in case of all requests already were handled, calls to force shutdown. another goes to force
214 * shutdown only when either all request will be handled or graceful shutdown will be time out.
216 synchronized void gracefulShutdown(){
217 isGracefulShutdown.set(true);
218 if(registry.isEmpty()){
223 LOG.info("Core manager::graceful shutdown is starting... this <" + this + ">");
224 wait(shutdownTimeout);
225 LOG.info("Core manager::graceful shutdown is continue... this <" + this + ">");
227 } catch (InterruptedException e) {
235 * Closes Protocol, stops Queue Manager and shutdowns Time Service.
237 private void forceShutdown(){
238 isForceShutdown = true;
240 LOG.info("Starting shutdown process.");
242 queueManager.stopQueueManager();
243 timerService.shutdown();
244 } catch (InterruptedException e) {
245 LOG.info("Client library shutdown in progress ", e);
251 * @return - true when shutdown is in process
253 boolean isShutdownInProgress(){
254 return isForceShutdown || isGracefulShutdown.get();
258 * Timeout handler implementation.
259 * This handler is responsible to assign a task for handling of timeout events.
262 private class TimeoutHandlerImpl implements ITimeoutHandler {
264 private final String corrID;
266 TimeoutHandlerImpl(String corrID) {
267 this.corrID = corrID;
271 * When a timeout event is occurring, the new Timeout task will be assigned into a queue,
272 * this queue is shared between both timeout and handlers which belong to same correlation ID.
275 public void onTimeout() {
277 submitTask(corrID, new Runnable() {
280 RequestResponseHandler requestResponseHandler = unregisterHandler(corrID);
281 if (requestResponseHandler != null) {
282 requestResponseHandler.onTimeOut();
286 } catch (InterruptedException e) {
287 LOG.warn("could not submit timeout task for correlation ID <" + corrID + "> ", e);
294 * Wakes Up graceful shutdown.
296 class EmptyRegistryCallbackImpl implements CoreRegistry.EmptyRegistryCallback {
298 public synchronized void emptyCallback() {
299 LOG.info("Registry is empty, wake up the shutdown!, isGraceful flag <" + isGracefulShutdown + ">");
300 if(isGracefulShutdown.get()){
307 * wakes up waiting shutdown.
309 private synchronized void wakeUpShutdown(){