2 * ============LICENSE_START==========================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * ============LICENSE_END=============================================
21 * ====================================================================
24 package org.onap.music.lockingservice.zookeeper;
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.eelf.logging.EELFLoggerDelegate;
33 import org.onap.music.eelf.logging.format.AppMessages;
34 import org.onap.music.eelf.logging.format.ErrorSeverity;
35 import org.onap.music.eelf.logging.format.ErrorTypes;
36 import org.onap.music.lockingservice.zookeeper.ZooKeeperOperation;
38 import java.util.List;
39 import java.util.concurrent.atomic.AtomicBoolean;
42 * A base class for protocol implementations which provides a number of higher level helper methods
43 * for working with ZooKeeper along with retrying synchronous operations if the connection to
44 * ZooKeeper closes such as {@link #retryOperation(ZooKeeperOperation)}
47 class ProtocolSupport {
48 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProtocolSupport.class);
50 protected ZooKeeper zookeeper;
51 private AtomicBoolean closed = new AtomicBoolean(false);
52 private long retryDelay = 500L;
53 private int retryCount = 10;
54 private List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
57 * Closes this strategy and releases any ZooKeeper resources; but keeps the ZooKeeper instance
61 if (closed.compareAndSet(false, true)) {
67 * return zookeeper client instance
69 * @return zookeeper client instance
71 public ZooKeeper getZookeeper() {
76 * return the acl its using
80 public List<ACL> getAcl() {
87 * @param acl the acl to set to
89 public void setAcl(List<ACL> acl) {
94 * get the retry delay in milliseconds
96 * @return the retry delay
98 public long getRetryDelay() {
103 * Sets the time waited between retry delays
105 * @param retryDelay the retry delay
107 public void setRetryDelay(long retryDelay) {
108 this.retryDelay = retryDelay;
112 * Allow derived classes to perform some custom closing operations to release resources
114 protected void doClose() {
115 throw new UnsupportedOperationException();
120 * Perform the given operation, retrying if the connection fails
122 * @return object. it needs to be cast to the callee's expected return type.
123 * @param operation FILL IN
124 * @throws KeeperException FILL IN
125 * @throws InterruptedException FILL IN
127 protected Object retryOperation(ZooKeeperOperation operation)
128 throws KeeperException, InterruptedException {
129 KeeperException exception = null;
130 for (int i = 0; i < retryCount; i++) {
132 return operation.execute();
133 } catch (KeeperException.SessionExpiredException e) {
134 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.SESSIONEXPIRED+" for: " + zookeeper + " so reconnecting due to: " + e, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
136 } catch (KeeperException.ConnectionLossException e) {
137 if (exception == null) {
140 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
141 logger.error(EELFLoggerDelegate.errorLogger, e,"Attempt " + i + " failed with connection loss so attempting to reconnect: " + e);
146 if(exception == null)
148 throw new NullPointerException();
156 * Ensures that the given path exists with no data, the current ACL and no flags
158 * @param path the lock path
160 protected void ensurePathExists(String path) {
161 ensureExists(path, null, acl, CreateMode.PERSISTENT);
165 * Ensures that the given path exists with the given data, ACL and flags
167 * @param path the lock path
168 * @param data the data
169 * @param acl list of ACLs applying to the path
170 * @param flags create mode flags
172 protected void ensureExists(final String path, final byte[] data, final List<ACL> acl,
173 final CreateMode flags) {
175 retryOperation(new ZooKeeperOperation() {
176 public boolean execute() throws KeeperException, InterruptedException {
177 Stat stat = zookeeper.exists(path, false);
181 zookeeper.create(path, data, acl, flags);
185 } catch (KeeperException e) {
186 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
187 } catch (InterruptedException e) {
188 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
193 * Returns true if this protocol has been closed
195 * @return true if this protocol is closed
197 protected boolean isClosed() {
202 * Performs a retry delay if this is not the first attempt
204 * @param attemptCount the number of the attempts performed so far
206 protected void retryDelay(int attemptCount) {
207 if (attemptCount > 0) {
209 Thread.sleep(attemptCount * retryDelay);
210 } catch (InterruptedException e) {
211 logger.error(EELFLoggerDelegate.errorLogger, e,AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
212 logger.error(EELFLoggerDelegate.errorLogger, e,"Thread failed to sleep: " + e);
213 Thread.currentThread().interrupt();