38606d00e925308c3b3ddca29de0c44350319945
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / cassandra / CassandraClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.dao.cassandra;
22
23 import java.util.List;
24
25 import javax.annotation.PreDestroy;
26
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.openecomp.sdc.be.config.ConfigurationManager;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.stereotype.Component;
32
33 import com.datastax.driver.core.Cluster;
34 import com.datastax.driver.core.Session;
35 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
36 import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
37 import com.datastax.driver.core.policies.DefaultRetryPolicy;
38 import com.datastax.driver.core.policies.LoadBalancingPolicy;
39 import com.datastax.driver.core.policies.TokenAwarePolicy;
40 import com.datastax.driver.mapping.Mapper;
41 import com.datastax.driver.mapping.MappingManager;
42
43 import fj.data.Either;
44
45 @Component("cassandra-client")
46 public class CassandraClient {
47         private static Logger logger = LoggerFactory.getLogger(CassandraClient.class.getName());
48
49         private Cluster cluster;
50         private boolean isConnected;
51
52         public CassandraClient() {
53                 super();
54                 isConnected = false;
55                 List<String> cassandraHosts = null;
56                 try {
57                         cassandraHosts = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
58                                         .getCassandraHosts();
59                         Long reconnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
60                                         .getCassandraConfig().getReconnectTimeout();
61
62                         logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
63                         Cluster.Builder clusterBuilder = Cluster.builder()
64                                         .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
65                                         .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
66
67                         cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
68                         enableAuthentication(clusterBuilder);
69                         enableSsl(clusterBuilder);
70                         setLocalDc(clusterBuilder);
71
72                         cluster = clusterBuilder.build();
73                         isConnected = true;
74                 } catch (Exception e) {
75                         logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
76                 }
77
78                 logger.info("** CassandraClient created");
79         }
80
81         private void setLocalDc(Cluster.Builder clusterBuilder) {
82                 String localDataCenter = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
83                                 .getLocalDataCenter();
84                 if (localDataCenter != null) {
85                         logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.",
86                                         localDataCenter);
87                         LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
88                                         DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
89                         clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
90                 } else {
91                         logger.info(
92                                         "localDatacenter was provided,  the driver will use the datacenter of the first contact point that was reached at initialization");
93                 }
94         }
95
96         private void enableSsl(Cluster.Builder clusterBuilder) {
97                 boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
98                 if (ssl) {
99                         String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
100                                         .getCassandraConfig().getTruststorePath();
101                         String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
102                                         .getCassandraConfig().getTruststorePassword();
103                         if (truststorePath == null || truststorePassword == null) {
104                                 logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
105                         } else {
106                                 System.setProperty("javax.net.ssl.trustStore", truststorePath);
107                                 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
108                                 clusterBuilder.withSSL();
109                         }
110
111                 }
112         }
113
114         private void enableAuthentication(Cluster.Builder clusterBuilder) {
115                 boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
116                                 .isAuthenticate();
117                 if (authenticate) {
118                         String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
119                                         .getUsername();
120                         String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
121                                         .getPassword();
122                         if (username == null || password == null) {
123                                 logger.error("authentication is enabled but username or password were not supplied.");
124                         } else {
125                                 clusterBuilder.withCredentials(username, password);
126                         }
127
128                 }
129         }
130
131         /**
132          * 
133          * @param keyspace
134          *            - key space to connect
135          * @return
136          */
137         public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) {
138                 if (cluster != null) {
139                         try {
140                                 Session session = cluster.connect(keyspace);
141                                 if (session != null) {
142                                         MappingManager manager = new MappingManager(session);
143                                         return Either.left(new ImmutablePair<Session, MappingManager>(session, manager));
144                                 } else {
145                                         return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
146                                 }
147                         } catch (Throwable e) {
148                                 logger.debug("Failed to connect to keyspace [{}], error :", keyspace, e);
149                                 return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
150                         }
151                 }
152                 return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
153         }
154
155         public <T> CassandraOperationStatus save(T entity, Class<T> clazz, MappingManager manager) {
156                 if (!isConnected) {
157                         return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
158                 }
159                 try {
160                         Mapper<T> mapper = manager.mapper(clazz);
161                         mapper.save(entity);
162                 } catch (Exception e) {
163                         logger.debug("Failed to save entity [{}], error :", entity, e);
164                         return CassandraOperationStatus.GENERAL_ERROR;
165                 }
166                 return CassandraOperationStatus.OK;
167         }
168
169         public <T> Either<T, CassandraOperationStatus> getById(String id, Class<T> clazz, MappingManager manager) {
170                 if (!isConnected) {
171                         return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
172                 }
173                 try {
174                         Mapper<T> mapper = manager.mapper(clazz);
175                         T result = mapper.get(id);
176                         if (result == null) {
177                                 return Either.right(CassandraOperationStatus.NOT_FOUND);
178                         }
179                         return Either.left(result);
180                 } catch (Exception e) {
181                         logger.debug("Failed to get by Id [{}], error :", id, e);
182                         return Either.right(CassandraOperationStatus.GENERAL_ERROR);
183                 }
184         }
185
186         public <T> CassandraOperationStatus delete(String id, Class<T> clazz, MappingManager manager) {
187                 if (!isConnected) {
188                         return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
189                 }
190                 try {
191                         Mapper<T> mapper = manager.mapper(clazz);
192                         mapper.delete(id);
193                 } catch (Exception e) {
194                         logger.debug("Failed to delete by id [{}], error :", id, e);
195                         return CassandraOperationStatus.GENERAL_ERROR;
196                 }
197                 return CassandraOperationStatus.OK;
198         }
199
200         public boolean isConnected() {
201                 return isConnected;
202         }
203
204         @PreDestroy
205         public void closeClient() {
206                 if (isConnected) {
207                         cluster.close();
208                 }
209                 logger.info("** CassandraClient cluster closed");
210         }
211 }