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