Fixed sonar issues in ProtocolSupport.java
[music.git] / src / main / java / org / onap / music / lockingservice / ProtocolSupport.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  *  Modifications Copyright (C) 2018 IBM.
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  * 
20  * ============LICENSE_END=============================================
21  * ====================================================================
22  */
23 package org.onap.music.lockingservice;
24
25 import org.apache.zookeeper.CreateMode;
26 import org.apache.zookeeper.KeeperException;
27 import org.apache.zookeeper.ZooDefs;
28 import org.apache.zookeeper.ZooKeeper;
29 import org.apache.zookeeper.data.ACL;
30 import org.apache.zookeeper.data.Stat;
31 import org.onap.music.eelf.logging.EELFLoggerDelegate;
32 import org.onap.music.eelf.logging.format.AppMessages;
33 import org.onap.music.eelf.logging.format.ErrorSeverity;
34 import org.onap.music.eelf.logging.format.ErrorTypes;
35 import org.onap.music.lockingservice.ZooKeeperOperation;
36 import java.util.List;
37 import java.util.concurrent.atomic.AtomicBoolean;
38
39 /**
40  * A base class for protocol implementations which provides a number of higher level helper methods
41  * for working with ZooKeeper along with retrying synchronous operations if the connection to
42  * ZooKeeper closes such as {@link #retryOperation(ZooKeeperOperation)}
43  *
44  */
45 class ProtocolSupport {
46     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProtocolSupport.class);
47
48     protected ZooKeeper zookeeper;
49     private AtomicBoolean closed = new AtomicBoolean(false);
50     private long retryDelay = 500L;
51     private int retryCount = 10;
52     private List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
53
54     /**
55      * Closes this strategy and releases any ZooKeeper resources; but keeps the ZooKeeper instance
56      * open
57      */
58     public void close() {
59         if (closed.compareAndSet(false, true)) {
60             doClose();
61         }
62     }
63
64     /**
65      * return zookeeper client instance
66      * 
67      * @return zookeeper client instance
68      */
69     public ZooKeeper getZookeeper() {
70         return zookeeper;
71     }
72
73     /**
74      * return the acl its using
75      * 
76      * @return the acl.
77      */
78     public List<ACL> getAcl() {
79         return acl;
80     }
81
82     /**
83      * set the acl
84      * 
85      * @param acl the acl to set to
86      */
87     public void setAcl(List<ACL> acl) {
88         this.acl = acl;
89     }
90
91     /**
92      * get the retry delay in milliseconds
93      * 
94      * @return the retry delay
95      */
96     public long getRetryDelay() {
97         return retryDelay;
98     }
99
100     /**
101      * Sets the time waited between retry delays
102      * 
103      * @param retryDelay the retry delay
104      */
105     public void setRetryDelay(long retryDelay) {
106         this.retryDelay = retryDelay;
107     }
108
109     /**
110      * Allow derived classes to perform some custom closing operations to release resources
111      */
112     protected void doClose() {
113         throw new UnsupportedOperationException();
114     }
115
116
117     /**
118      * Perform the given operation, retrying if the connection fails
119      * 
120      * @return object. it needs to be cast to the callee's expected return type.
121      * @param operation FILL IN
122      * @throws KeeperException FILL IN
123      * @throws InterruptedException FILL IN
124      */
125     protected Object retryOperation(ZooKeeperOperation operation)
126                     throws KeeperException, InterruptedException {
127         KeeperException exception = null;
128         for (int i = 0; i < retryCount; i++) {
129             try {
130                 return operation.execute();
131             } catch (KeeperException.SessionExpiredException e) {
132                 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.SESSIONEXPIRED+" for: " + zookeeper + " so reconnecting due to: " + e, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
133                 throw e;
134             } catch (KeeperException.ConnectionLossException e) {
135                 if (exception == null) {
136                     exception = e;
137                 }
138                 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
139                 logger.error(EELFLoggerDelegate.errorLogger, e,"Attempt " + i + " failed with connection loss so attempting to reconnect: " + e);
140                 
141                 retryDelay(i);
142             }
143         }
144         if(exception == null)
145             {
146               throw new NullPointerException();
147             }
148         else{
149             throw exception;
150             }
151     }
152
153     /**
154      * Ensures that the given path exists with no data, the current ACL and no flags
155      * 
156      * @param path the lock path
157      */
158     protected void ensurePathExists(String path)  {
159         ensureExists(path, null, acl, CreateMode.PERSISTENT);
160     }
161
162     /**
163      * Ensures that the given path exists with the given data, ACL and flags
164      * 
165      * @param path the lock path
166      * @param data the data
167      * @param acl list of ACLs applying to the path
168      * @param flags create mode flags
169      */
170     protected void ensureExists(final String path, final byte[] data, final List<ACL> acl,
171                     final CreateMode flags)  {
172         try {
173             retryOperation(new ZooKeeperOperation() {
174                 public boolean execute() throws KeeperException, InterruptedException {
175                     Stat stat = zookeeper.exists(path, false);
176                     if (stat != null) {
177                         return true;
178                     }
179                     zookeeper.create(path, data, acl, flags);
180                     return true;
181                 }
182             });
183         } catch (KeeperException e) {
184                 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
185         } catch (InterruptedException e) {
186                 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
187                 
188         }
189     }
190
191     /**
192      * Returns true if this protocol has been closed
193      * 
194      * @return true if this protocol is closed
195      */
196     protected boolean isClosed() {
197         return closed.get();
198     }
199
200     /**
201      * Performs a retry delay if this is not the first attempt
202      * 
203      * @param attemptCount the number of the attempts performed so far
204      */
205     protected void retryDelay(int attemptCount) {
206         if (attemptCount > 0) {
207             try {
208                 Thread.sleep(attemptCount * retryDelay);
209             } catch (InterruptedException e) {
210                 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
211                 logger.error(EELFLoggerDelegate.errorLogger, e,"Thread failed to sleep: " + e);
212                 Thread.currentThread().interrupt();
213             }
214         }
215     }
216 }