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