aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
blob: c343765c5cede755a2e54b2fd803ee9d7102a9e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.dao.cassandra;

import java.util.List;

import javax.annotation.PreDestroy;

import com.datastax.driver.core.SocketOptions;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.DefaultRetryPolicy;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;

import fj.data.Either;

@Component("cassandra-client")
public class CassandraClient {
	private static Logger logger = LoggerFactory.getLogger(CassandraClient.class.getName());

	private Cluster cluster;
	private boolean isConnected;

	public CassandraClient() {
		super();
		isConnected = false;
		List<String> cassandraHosts = null;
		try {
			cassandraHosts = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
					.getCassandraHosts();
			Long reconnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
					.getCassandraConfig().getReconnectTimeout();

			logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
			Cluster.Builder clusterBuilder = Cluster.builder()
					.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
					.withRetryPolicy(DefaultRetryPolicy.INSTANCE);

			cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
			setSocketOptions(clusterBuilder);
			enableAuthentication(clusterBuilder);
			enableSsl(clusterBuilder);
			setLocalDc(clusterBuilder);

			cluster = clusterBuilder.build();
			isConnected = true;
		} catch (Exception e) {
			logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
		}

		logger.info("** CassandraClient created");
	}

	private void setSocketOptions(Cluster.Builder clusterBuilder) {
		SocketOptions socketOptions =new SocketOptions();
		Integer socketConnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getSocketConnectTimeout();
		if( socketConnectTimeout!=null ){
			logger.info("SocketConnectTimeout was provided, setting Cassandra client to use SocketConnectTimeout: {} .",socketConnectTimeout);
			socketOptions.setConnectTimeoutMillis(socketConnectTimeout);
		}
		Integer socketReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getSocketReadTimeout();
		if( socketReadTimeout != null ){
			logger.info("SocketReadTimeout was provided, setting Cassandra client to use SocketReadTimeout: {} .",socketReadTimeout);
			socketOptions.setReadTimeoutMillis(socketReadTimeout);
		}
		clusterBuilder.withSocketOptions(socketOptions);
	}

	private void setLocalDc(Cluster.Builder clusterBuilder) {
		String localDataCenter = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
				.getLocalDataCenter();
		if (localDataCenter != null) {
			logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.",
					localDataCenter);
			LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
					DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
			clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
		} else {
			logger.info(
					"localDatacenter was provided,  the driver will use the datacenter of the first contact point that was reached at initialization");
		}
	}

	private void enableSsl(Cluster.Builder clusterBuilder) {
		boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
		if (ssl) {
			String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
					.getCassandraConfig().getTruststorePath();
			String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
					.getCassandraConfig().getTruststorePassword();
			if (truststorePath == null || truststorePassword == null) {
				logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
			} else {
				System.setProperty("javax.net.ssl.trustStore", truststorePath);
				System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
				clusterBuilder.withSSL();
			}

		}
	}

	private void enableAuthentication(Cluster.Builder clusterBuilder) {
		boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
				.isAuthenticate();
		if (authenticate) {
			String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
					.getUsername();
			String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
					.getPassword();
			if (username == null || password == null) {
				logger.error("authentication is enabled but username or password were not supplied.");
			} else {
				clusterBuilder.withCredentials(username, password);
			}

		}
	}

	/**
	 * 
	 * @param keyspace
	 *            - key space to connect
	 * @return
	 */
	public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) {
		if (cluster != null) {
			try {
				Session session = cluster.connect(keyspace);
				if (session != null) {
					MappingManager manager = new MappingManager(session);
					return Either.left(new ImmutablePair<Session, MappingManager>(session, manager));
				} else {
					return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
				}
			} catch (Throwable e) {
				logger.debug("Failed to connect to keyspace [{}], error :", keyspace, e);
				return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
			}
		}
		return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
	}

	public <T> CassandraOperationStatus save(T entity, Class<T> clazz, MappingManager manager) {
		if (!isConnected) {
			return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
		}
		try {
			Mapper<T> mapper = manager.mapper(clazz);
			mapper.save(entity);
		} catch (Exception e) {
			logger.debug("Failed to save entity [{}], error :", entity, e);
			return CassandraOperationStatus.GENERAL_ERROR;
		}
		return CassandraOperationStatus.OK;
	}

	public <T> Either<T, CassandraOperationStatus> getById(String id, Class<T> clazz, MappingManager manager) {
		if (!isConnected) {
			return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
		}
		try {
			Mapper<T> mapper = manager.mapper(clazz);
			T result = mapper.get(id);
			if (result == null) {
				return Either.right(CassandraOperationStatus.NOT_FOUND);
			}
			return Either.left(result);
		} catch (Exception e) {
			logger.debug("Failed to get by Id [{}], error :", id, e);
			return Either.right(CassandraOperationStatus.GENERAL_ERROR);
		}
	}

	public <T> CassandraOperationStatus delete(String id, Class<T> clazz, MappingManager manager) {
		if (!isConnected) {
			return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
		}
		try {
			Mapper<T> mapper = manager.mapper(clazz);
			mapper.delete(id);
		} catch (Exception e) {
			logger.debug("Failed to delete by id [{}], error :", id, e);
			return CassandraOperationStatus.GENERAL_ERROR;
		}
		return CassandraOperationStatus.OK;
	}

	public boolean isConnected() {
		return isConnected;
	}

	@PreDestroy
	public void closeClient() {
		if (isConnected) {
			cluster.close();
		}
		logger.info("** CassandraClient cluster closed");
	}
}